import { useRef, useState, useCallback, useEffect } from 'react'
/* 带查询的分页加载长列表 */

/**
 * @param {*} defaultQuery 表单查询默认参数
 * @param {*} api
 */
function useQueryTable(defaultQuery = {}, api) {
	/* 保存查询表格表单信息 */
	const formData = useRef({})
	/* 分页信息 */
	const pagination = useRef({
		page: defaultQuery.page || 1,
		pageSize: defaultQuery.pageSize || 10,
	})
	/* 强制更新 */
	const [, forceUpdate] = useState(null)

	/* 表格数据 */
	const [tableData, setTableData] = useState({
		data: [],
		total: 0,
		current: 1,
	})
	/* 请求表格数据 */
	const getList = useCallback(
		async function (payload = {}) {
			if (!api) return
			const data = (await api({
				...defaultQuery,
				...payload,
				...pagination.current,
				...formData.current,
			})) || {
				code: 200,
				list: [],
				current: 1,
				total: 1,
			}
			if (data.code === 200) {
				setTableData({
					list: data.list,
					current: data.current,
					total: data.total,
				})
			}
		},
		[api]
	) /*  以api作为依赖项 当api改变时，重新声明getList */

	/* 改变表单单元项 */
	const setFormItem = useCallback(function (key, value) {
		const form = formData.current
		form[key] = value
		forceUpdate({}) /* 每一次都能更新，不会造城 state 相等的情况 */
	}, [])

	/* 重置表单 */
	const reset = useCallback(
		function () {
			const current = formData.current
			Object.keys(current).forEach((key) => {
				current[key] = ''
			})
			pagination.current = {
				page: defaultQuery.page || 1,
				pageSize: defaultQuery.pageSize || 10,
			}
			/* 请求数据 */
			getList()
		},
		[getList]
	)

	/* 处理分页逻辑 */
	const handleChange = useCallback(
		async function (page, pageSize) {
			pagination.current = {
				page,
				pageSize,
			}
			getList()
		},
		[getList]
	)
	useEffect(() => {
		getList()
	}, [])
	/* 组合暴露参数 */
	return [
		{
			tableData,
			handleChange,
			getList,
			pagination: pagination.current,
		},
		{
			formData: formData.current,
			setFormItem,
			reset,
		},
	]
}

export default useQueryTable
